﻿using AutoMapper;
using BS.Domain.RBAC;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;
using System.Transactions;

namespace BS.Write.Api.Handler.RBAC
{
    public class AddUserToRoleCommandHandler : IRequestHandler<AddUserToRoleCommand, ApiResult>
    {
        private readonly ILogger<AddUserToRoleCommandHandler> _logger;

        private readonly IUserRepository _userRepository;

        private readonly IRoleRepository _roleRepository;

        private readonly IMapper _mapper;
        public AddUserToRoleCommandHandler(ILogger<AddUserToRoleCommandHandler> logger, IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper)
        {
            _logger = logger;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(AddUserToRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                
                var usersDto = _mapper.Map<UserInfo>(request);
                var result = await _userRepository.InsertUserWithRole(usersDto,request.RoleIds);
                var resultAll=await _userRepository.GetAllAsync(x=>x.IsDeleted==false&&x.UserName==request.UserName);
                return await Task.FromResult(ApiResult.Ok(resultAll));
                
            }
            catch (Exception ex)
            {
                //scope.Dispose();
                _logger.LogError(ex, "AddUserToRoleCommandHandler");
                return await Task.FromResult(ApiResult.Fail(ex.Message));
            }
        }           
    }
}
public class AddUserToRoleCommand:IRequest<ApiResult>
{
        public string UserName { get; set; } = string.Empty;

        public string Password { get; set; } = string.Empty;

        /// <summary>
        /// 每增加一个用户选一个角色
        /// </summary>
        public int[] RoleIds { get; set; } = new int[] { };
}
